package top.sdaily.business.service.engineer.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.sdaily.business.mapper.engineer.EngineerTagMapper;
import top.sdaily.business.model.engineer.Engineer;
import top.sdaily.business.model.engineer.EngineerTag;
import top.sdaily.business.model.engineer.Tag;
import top.sdaily.business.service.engineer.TagService;
import top.sdaily.core.mybatis.Conditions;
import top.sdaily.core.service.BaseServiceImpl;
import top.sdaily.core.utils.ArrayUtils;
import top.sdaily.core.utils.IdGeneratorUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by soya on 2017/2/9.
 */
@Service
@Transactional
public class TagServiceImpl extends BaseServiceImpl<Tag> implements TagService {

    @Autowired
    EngineerTagMapper engineerTagMapper;

    public List<Tag> createNotExistsTags(String[] names){
        List<Tag> tags = super.findList(new Conditions(Tag.class).in("name",names));
        String[] exists = new String[tags.size()];
        for (int i=0; i<tags.size(); i++){
            exists[i] = tags.get(i).getName();
        }

        if (exists.length == names.length){
            return tags;
        }

        List<String> notExistsNames = ArrayUtils.compareDifferent(exists, names);

        List<Tag> newTags = new ArrayList<Tag>();
        Tag tag;
        for(String name : notExistsNames ) {
            tag = new Tag();
            tag.setPkid(IdGeneratorUtils.fresh());
            tag.setName(name);
            newTags.add(tag);
        }

        super.insertBatch(newTags);
        newTags.addAll(tags);
        return newTags;
    }

    @Override
    public void saveEngineerTag(String engineerId, String[] names){

        List<Tag> tags = createNotExistsTags(names);

        engineerTagMapper.delete(new Conditions(EngineerTag.class).eq("engineer_id", engineerId));

        List<EngineerTag> links = new ArrayList<EngineerTag>();
        EngineerTag engineerTag;
        for (Tag tag : tags) {
            engineerTag = new EngineerTag();
            engineerTag.setPkid(IdGeneratorUtils.fresh());
            engineerTag.setEngineerId(engineerId);
            engineerTag.setTagId(tag.getPkid());
            links.add(engineerTag);
        }
        if(names.length > 0){
            engineerTagMapper.insertBatch(links);
        }
    }
}
